package com.newcapec.common.utils.iot;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.time.DateFormatUtils;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Pattern;

public class StringUtil {

    /**
     * 字符串左补0公用方法
     *
     * @param str
     * @param length
     * @return
     */
    public static String formatStr(String str, int length) {
        if (str == null) {
            str = "";
        }
        int strLen = str.getBytes().length;
        if (strLen == length) {
            return str;
        } else if (strLen < length) {
            int temp = length - strLen;
            String tem = "";
            for (int i = 0; i < temp; i++) {
                tem = tem + "0";
            }
            return tem + str;
        } else {
            return str.substring(0, length);
        }
    }

    /**
     * ASCII转String
     *
     * @param hex
     * @return
     */
    public static String convertHexToString(String hex) {

        StringBuilder sb = new StringBuilder();
        StringBuilder temp = new StringBuilder();

        // 49204c6f7665204a617661 split into two characters 49, 20, 4c...
        for (int i = 0; i < hex.length() - 1; i += 2) {

            // grab the hex in pairs
            String output = hex.substring(i, (i + 2));

            if (!"00".equals(output)) {
                // convert hex to decimal
                int decimal = Integer.parseInt(output, 16);
                // convert the decimal to character
                sb.append((char) decimal);

                temp.append(decimal);
            }
        }

        return sb.toString();
    }

    public static HashMap<String, Object> toHashMap(Object object) {
        HashMap<String, Object> data = new HashMap<String, Object>();
        // 将json字符串转换成jsonObject
        JSONObject jsonObject = (JSONObject) JSONObject.toJSON(object);
        final Set<Map.Entry<String, Object>> entries = jsonObject.entrySet();
        // 遍历jsonObject数据，添加到Map对象
        for (Map.Entry<String, Object> one : entries) {
            data.put(one.getKey(), one.getValue());
        }
        return data;
    }

    /**
     * 转化字符串为十六进制编码 hehongchao 2017-6-8
     *
     * @param s
     * @return
     */
    public static String toHexString(String s) {
        String str = "";
        for (int i = 0; i < s.length(); i++) {
            int ch = (int) s.charAt(i);
            String s4 = Integer.toHexString(ch);
            str = str + s4;
        }
        return str;
    }

    /***
     * 生成虚拟卡 卡唯一序列号
     *
     * @return
     */
    public static String GetVScardsnr() {

        Random random = new Random();
        byte[] bytes = new byte[4];

        random.nextBytes(bytes);

        String s = ByteUtil.ByteArrayToHexStr(bytes, 0, bytes.length, (byte) 0);

        String t = s.replace(s.substring(0, 1), "E");

        long ss = Long.parseLong(t, 16);// 16进制转10进制

        String two = Long.toBinaryString(ss);// 10进制转2进制

        int total = 0;
        char[] chrCharArray = two.toCharArray();
        for (int i = 1; i < two.length(); i++) {
            total += Integer.parseInt(String.valueOf(chrCharArray[i]));
        }

        // 2进制取后31位奇偶和作为最后一位
        String end = two.substring(0, 31) + (total % 2);

        long ten = Long.parseLong(end, 2);// 2进制转10进制

        String scandsnr = Long.toHexString(ten).toUpperCase();// 10进制转16进制

        return scandsnr;
    }

    /**
     * 字符串右补0公用方法
     *
     * @param str
     * @param length
     * @return
     */
    public static String addZeroForNum(String str, int length) {
        if (str == null) {
            str = "";
        }
        int strLen = str.getBytes().length;
        if (strLen == length) {
            return str;
        } else if (strLen < length) {
            int temp = length - strLen;
            String tem = "";
            for (int i = 0; i < temp; i++) {
                tem = tem + "0";
            }
            return str + tem;
        } else {
            return str.substring(0, length);
        }
    }

    public static boolean isNumber(String content) {
        String partten = "^[0-9]*$";
        return Pattern.matches(partten, content);
    }

    /**
     * 产生32位随机数
     *
     * @param length
     * @return
     */
    public static String getRandomString(int length) {
        // 产生随机数
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        // 循环length次
        for (int i = 0; i < length; i++) {
            // 产生0-2个随机数，既与a-z，A-Z，0-9三种可能
            int number = random.nextInt(3);
            long result = 0;
            switch (number) {
                // 如果number产生的是数字0；
                case 0:
                    // 产生A-Z的ASCII码
                    result = Math.round(Math.random() * 25 + 65);
                    // 将ASCII码转换成字符
                    sb.append(String.valueOf((char) result));
                    break;
                case 1:
                    // 产生a-z的ASCII码
                    result = Math.round(Math.random() * 25 + 97);
                    sb.append(String.valueOf((char) result));
                    break;
                case 2:
                    // 产生0-9的数字
                    sb.append(String.valueOf(new Random().nextInt(10)));
                    break;
            }
        }
        return sb.toString();
    }

    /**
     * 字符串转成acsii码字节数组
     *
     * @param str
     * @return
     * @throws UnsupportedEncodingException
     */
    public static byte[] str2Ascii2bytes(String str) throws UnsupportedEncodingException {
        return str.getBytes("US-ASCII");
    }

    public static byte[] intToByteArray(int a) {
        return new byte[]{(byte) ((a >> 24) & 0xFF), (byte) ((a >> 16) & 0xFF), (byte) ((a >> 8) & 0xFF), (byte) (a & 0xFF)};
    }

    public static String byte2HexString(byte[] bytes) {
        StringBuilder buf = new StringBuilder(bytes.length * 2);
        for (byte b : bytes) {
            buf.append(String.format("%02x", new Integer(b & 0xff)));
        }
        return buf.toString().toUpperCase();
    }

    public static byte hexToByte(String inHex) {
        return (byte) Integer.parseInt(inHex, 16);
    }

    public static byte[] hexToByteArray(String inHex) {
        int hexlen = inHex.length();
        byte[] result;
        if (hexlen % 2 == 1) {
            // 奇数
            hexlen++;
            result = new byte[(hexlen / 2)];
            inHex = "0" + inHex;
        } else {
            // 偶数
            result = new byte[(hexlen / 2)];
        }
        int j = 0;
        for (int i = 0; i < hexlen; i += 2) {
            result[j] = hexToByte(inHex.substring(i, i + 2));
            j++;
        }
        return result;
    }

    /**
     * 生成十位一卡通芯片号
     * <p>
     * 使用场景：支付宝代扣场景，认证接口需要使用ONLINE_BASE_ACCOUNT表SCARDSNR字段
     *
     * @param prefix 字符前缀
     * @return
     */
    public static String generateScardSNR(String prefix) {

        Random random = new Random();
        byte[] bytes = new byte[6];

        random.nextBytes(bytes);

        String s = ByteUtil.ByteArrayToHexStr(bytes, 0, bytes.length, (byte) 0);

        String t = s.replace(s.substring(0, 1), prefix);

        long ss = Long.parseLong(t, 16);// 16进制转10进制

        String two = Long.toBinaryString(ss);// 10进制转2进制

        int total = 0;
        char[] chrCharArray = two.toCharArray();
        for (int i = 1; i < two.length(); i++) {
            total += Integer.parseInt(String.valueOf(chrCharArray[i]));
        }

        // 2进制取后31位奇偶和作为最后一位(8位字符串)
        // 2进制后取39位奇偶和作为最后一位(10位字符串)
        String end = two.substring(0, 39) + (total % 2);

        long ten = Long.parseLong(end, 2);// 2进制转10进制

        String scandsnr = Long.toHexString(ten).toUpperCase();// 10进制转16进制

        return scandsnr;
    }

    /**
     * @param nowDate   要比较的时间
     * @param startDate 开始时间
     * @param endDate   结束时间
     * @return true在时间段内，false不在时间段内
     * @throws Exception
     */
    public static boolean hourMinuteBetween(String nowDate, String startDate, String endDate) throws Exception {

        SimpleDateFormat format = new SimpleDateFormat("HH:mm");

        Date now = format.parse(nowDate);
        Date start = format.parse(startDate);
        Date end = format.parse(endDate);

        long nowTime = now.getTime();
        long startTime = start.getTime();
        long endTime = end.getTime();

        return nowTime >= startTime && nowTime <= endTime;
    }

    /**
     * 生成指定位数的随机数
     *
     * @param length
     * @return
     */
    public static String getRandom(int length) {
        String val = "";
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            val += String.valueOf(random.nextInt(10));
        }
        return val;
    }

    public static String getOrderno(int length) {
        Date now = new Date();
        String time = DateFormatUtils.format(now, "yyMMddHHmmss");
        String val = "";
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            val += String.valueOf(random.nextInt(10));
        }
        StringBuilder sb = new StringBuilder(time).append(val);
        return sb.toString();
    }

    public static void main(String[] args) {
        SimpleDateFormat df = new SimpleDateFormat("HH:mm");// 设置日期格式
        String startdate = "00:00";
        String enddate = "13:16";

        Boolean flag;
        try {
            flag = hourMinuteBetween(df.format(new Date()), startdate, enddate);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("");
    }

}
